package com.abc.filter;

import com.abc.util.AESUtil;
import com.abc.util.RSAUtils;
import com.alibaba.fastjson.JSONObject;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * 第三步：返回结果加密操作
 *
 * @Description APP端，接口返回的数据进行加密处理
 */
public class AppRespEncryptFilter implements GatewayFilter, Ordered {

    private int order;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String bgDebug = exchange.getAttributeOrDefault(ConstantFilter.BG_DEBUG_KEY, ConstantFilter.REQ_RES_ENCRYPT);

        ServerHttpResponse originalResponse = exchange.getResponse();
        DataBufferFactory bufferFactory = originalResponse.bufferFactory();
        ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                if (body instanceof Flux) {
                    Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                    return super.writeWith(fluxBody.buffer().map(dataBuffer -> {

                        DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                        DataBuffer join = dataBufferFactory.join(dataBuffer);

                        byte[] content = new byte[join.readableByteCount()];
                        join.read(content);
                        //释放掉内存
                        DataBufferUtils.release(join);
                        // 正常返回的数据
                        String rootData = new String(content, Charset.forName("UTF-8"));
                        byte[] respData = rootData.getBytes();

                        if(ConstantFilter.REQ_RES_ENCRYPT.equals(bgDebug)){
                            // 对数据进行加密
                            //得到一个AES的密钥
//                            String randomKey = AESUtil.getRandomKey();
                            String randomKey = "abcdefg";
                            //AES通过此密钥进行加密
//                            String encryptData = AESUtil.AESEncrypt(rootData, randomKey, "CBC");
                            String encryptData = AESUtil.encrypt(rootData, randomKey);
                            //将AES密钥通过RSA公钥加密,存到k中（前端需要RSA私钥，得到AES密钥，解密数据）
                            //前端生成RSA密钥对
//                            String encryptRandomKey = RSAUtils.publicEncrypt(randomKey);
                            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCg3VX1svV1hW8oLnNUOhtpTH+2ogJkaveLRDcN46RkdoX6WCyFFVmPJjk5mFiwvTVuY7Y3WaK5GP66c27EsdU5VGbYJxedz1nSgx1Cr9bDK3FZRNwN0+0qsxQcTEAcidQqMntZT3ufxsLL+C83ee3otteU7x9bCT03BrMuB2RmhwIDAQAB";
                            String encryptRandomKey = null;
                            try {
                                encryptRandomKey = RSAUtils.encryptByPublicKey(publicKey, "abcdefg");
//                                String s = RSAUtils.decryptByPrivateKey("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKDdVfWy9XWFbyguc1Q6G2lMf7aiAmRq94tENw3jpGR2hfpYLIUVWY8mOTmYWLC9NW5jtjdZorkY/rpzbsSx1TlUZtgnF53PWdKDHUKv1sMrcVlE3A3T7SqzFBxMQByJ1Coye1lPe5/Gwsv4Lzd57ei215TvH1sJPTcGsy4HZGaHAgMBAAECgYAKJkzxJqx0EMo1p9ChBNWL7Ea2mDw8Z79cqx4qIy3RJOVJKV0NvI4dCRVdO+6EoDuJzoLFtUMeGKSh0PyxLmM8lCFQIgtiSu8l+iwe4IOoyBwAvS7EgCVdvCnOCE1CA0F/8FSY/b2RzNR+bbVcGAo/TgRuyTO4Mja+2AW4SkHJOQJBANWv975pVzrlz9EOFTaUd/U3taandZ/PYtB6KspRTMzXMVQKNirH5y+rDjBxj2V8AUVx3N9TIgHnIC8sv8tbJMsCQQDAt7ogRn4n5Y9WHbk6ctA1vkLHSF0VmkpMP8ogOFd56Egv0jFse8hKbeeehYQVyS0zIbEGyhfZR0n+jkYeMMm1AkAZRPPhGofsORz4NdggWjJNV0ct7AOm4FlpGelRf4e7eX8l1wdMy9L0+h91bxhsAdwMoEhkSGpvGyvdKEeN/rs9AkEAqnXYPBQeIkv6rME9xWUopWDU0FBBhYojja4eqsErHrlGoIXbEYmrb6om5SBT5LE9OazjWI4I6jcUTASsIKgmwQJAf3sRcw4R/pIpuHtOfZaLjeHcBb/pd86kK8aDuLCa3uyefcQ46PEigwiJKlj7f2/cshA+Bz6qqi753f26658IeQ==", encryptRandomKey);
//                                System.out.println(s);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            JSONObject json = new JSONObject();
                            json.put("k", encryptRandomKey);
                            json.put("v", encryptData);
                            respData = json.toJSONString().getBytes();
                        }

                        // 加密后的数据返回给客户端
                        byte[] uppedContent = new String(respData, Charset.forName("UTF-8")).getBytes();
                        return bufferFactory.wrap(uppedContent);
                    }));
                }
                return super.writeWith(body);
            }
        };
        return chain.filter(exchange.mutate().response(decoratedResponse).build());
    }

//    public static void main(String[] args) throws Exception {
//        String s = RSAUtils.decryptByPrivateKey("MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKDdVfWy9XWFbyguc1Q6G2lMf7aiAmRq94tENw3jpGR2hfpYLIUVWY8mOTmYWLC9NW5jtjdZorkY/rpzbsSx1TlUZtgnF53PWdKDHUKv1sMrcVlE3A3T7SqzFBxMQByJ1Coye1lPe5/Gwsv4Lzd57ei215TvH1sJPTcGsy4HZGaHAgMBAAECgYAKJkzxJqx0EMo1p9ChBNWL7Ea2mDw8Z79cqx4qIy3RJOVJKV0NvI4dCRVdO+6EoDuJzoLFtUMeGKSh0PyxLmM8lCFQIgtiSu8l+iwe4IOoyBwAvS7EgCVdvCnOCE1CA0F/8FSY/b2RzNR+bbVcGAo/TgRuyTO4Mja+2AW4SkHJOQJBANWv975pVzrlz9EOFTaUd/U3taandZ/PYtB6KspRTMzXMVQKNirH5y+rDjBxj2V8AUVx3N9TIgHnIC8sv8tbJMsCQQDAt7ogRn4n5Y9WHbk6ctA1vkLHSF0VmkpMP8ogOFd56Egv0jFse8hKbeeehYQVyS0zIbEGyhfZR0n+jkYeMMm1AkAZRPPhGofsORz4NdggWjJNV0ct7AOm4FlpGelRf4e7eX8l1wdMy9L0+h91bxhsAdwMoEhkSGpvGyvdKEeN/rs9AkEAqnXYPBQeIkv6rME9xWUopWDU0FBBhYojja4eqsErHrlGoIXbEYmrb6om5SBT5LE9OazjWI4I6jcUTASsIKgmwQJAf3sRcw4R/pIpuHtOfZaLjeHcBb/pd86kK8aDuLCa3uyefcQ46PEigwiJKlj7f2/cshA+Bz6qqi753f26658IeQ==", "dEYjqvALcGKvqUJ4B+Jc0RL6YM9oQW76WY791ZF4U61sY5RVXsVLOT3xHFtFKVHOWztWLBQ59YyMnRCJ+4Nm4kfy3s168g8MY660fstsIYAwlZZpgZ7QTiSbLMmpbS6DGkU05bCwSa6onVm5FQMhIT0/KIlAVjqVrBVRkIbn0Uk=");
//        System.out.println(s);
//    }

    @Override
    public int getOrder() {
        return this.order;
    }

    public AppRespEncryptFilter(int order){
        this.order = order;
    }
}